<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
    >
      <el-form-item label="合同名称" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入合同名称"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="录入时间">
        <el-date-picker
          v-model="queryParams.recordDateRange"
          style="width: 220px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="签订时间">
        <el-date-picker
          v-model="queryParams.singDateRange"
          style="width: 220px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="回款时间">
        <el-date-picker
          v-model="queryParams.paymentDateRange"
          style="width: 220px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </el-form-item>
      <el-form-item label="区域" prop="area">
        <el-input
          v-model="queryParams.area"
          placeholder="请输入区域"
          clearable
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        v-hasPermi="['system:settlements:productionDepartment']"
        label="生产部门"
      >
        <el-select
          v-model="queryParams.designDeptId"
          placeholder="请选择生产部门"
          clearable
          filterable
          style="width: 160px"
        >
          <el-option
            v-for="dept in deptList"
            :key="dept.deptId"
            :label="dept.deptName"
            :value="dept.deptId"
          />
        </el-select>
      </el-form-item>
      <el-form-item
        v-hasPermi="['system:settlements:MarketDevelopmentPersonnel']"
        label="市场拓展人员"
      >
        <el-select
          v-model="queryParams.marketExpansionUserId"
          placeholder="请选择市场拓展人员"
          clearable
          filterable
          remote
          :remote-method="filterMarketUser"
          style="width: 180px"
        >
          <el-option
            v-for="user in filteredMarketUserList"
            :key="user.userId"
            :label="user.nickName"
            :value="user.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="请选择项目类型"
          filterable
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="item in dict.type.project_types"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:settlements:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="handleSort"
        >排序</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:settlements:importContracts']"
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport('合同')"
        >导入合同信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:settlements:downloadContractTemplate']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('合同')"
        >合同模板下载</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:settlements:importPaymentRecordTemplate']"
          type="primary"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport('回款')"
        >导入回款记录信息</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:settlements:downloadPaymentRecordTemplate']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('回款')"
        >回款记录模板下载</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="contractList"
      border
      :row-class-name="tableRowClassName"
      @selection-change="handleSelectionChange"
    >
      <el-table-column label="序号" prop="no" />
      <el-table-column label="区（县）" prop="region" width="80" />
      <el-table-column label="业主单位" prop="organizationName" />
      <el-table-column label="项目名称" prop="projectName" />
      <el-table-column label="公司名称" prop="company" />
      <el-table-column label="合同金额（万元）" prop="money" width="100" />
      <el-table-column label="合同签订时间" prop="signTime" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.signTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目累计回款（万元）" prop="payment" width="100" />
      <el-table-column label="剩余合同额" prop="remainMoney" width="100" />
      <el-table-column label="设计责任部门">
        <el-table-column
          prop="projectDesignLeadUserName"
          label="项目设总"
          width="80"
        />
        <el-table-column prop="projectDesignLeadDeptNames" label="生产部门" />
      </el-table-column>
      <el-table-column label="备注" prop="remark" />
      <el-table-column
        label="录入时间"
        align="center"
        prop="recordTime"
        width="100"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.recordTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button
            v-hasPermi="['system:settlements:list']"
            size="mini"
            type="text"
            icon="el-icon-s-order"
            @click="handleListShow(scope.row)"
          >查看详情
          </el-button>
          <el-button
            v-hasPermi="['system:settlements:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['system:settlements:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
          <el-button
            v-hasPermi="['system:settlements:check']"
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handleViewAllocation(scope.row)"
          >合同应分配额查看
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-circle-check"
            @click="handlePaymentRecordDialog(scope.row)"
          >回款记录管理
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 合计行 -->
    <div style="margin: 10px 0; text-align: right">
      <span
        style="margin-right: 30px"
      >搜索时间回款额合计：<b>{{ paymentTimeMoney }}</b> 万元</span>
      <span
        style="margin-right: 30px"
      >合同额合计：<b>{{ totalMoney }}</b> 万元</span>
      <span>总回款额合计：<b>{{ totalPayment }}</b> 万元</span>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <contract-form-dialog
      :visible.sync="open"
      :title="title"
      :user-list="userList"
      :dept-list="deptList"
      :dict="dict"
      :edit-data="editData"
      @success="onContractFormSuccess"
      @cancel="open = false"
    />

    <el-dialog
      title="合同分配额"
      :visible.sync="allocationDialogVisible"
      width="50%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-divider content-position="center">各部门承担按合同应分配</el-divider>
      <el-table v-loading="allocationLoading" :data="allocationRecords">
        <el-table-column label="部门" prop="deptName" />
        <el-table-column label="分配比例" prop="rate" />
        <el-table-column label="分配金额（万元）" prop="allocationMoney" />
      </el-table>
      <el-divider content-position="center">市场拓展按合同应分配</el-divider>
      <el-table v-loading="allocationLoading" :data="allocationMarketRecords">
        <el-table-column label="部门或人员" prop="name">
          <template slot-scope="scope">
            {{
              scope.row.isDept
                ? scope.row.projectMarketExpansionDeptName
                : scope.row.projectMarketExpansionUserName
            }}
          </template>
        </el-table-column>
        <el-table-column label="分配比例" prop="marketExpansionRate" />
        <el-table-column label="分配金额（万元）" prop="marketExpansionMoney" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="allocationDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="合同回款记录"
      :visible.sync="paymentDialogVisible"
      width="100%"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['system:settlements:record:add']"
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handlePaymentRecordAdd"
          >新增
          </el-button>
        </el-col>
      </el-row>
      <el-table :key="paymentDialogVisible" v-loading="paymentRecordLoading" fit :data="paymentRecordList">
        <el-table-column
          label="回款时间"
          align="center"
          prop="paymentTime"
          width="100"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.paymentTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
        <el-table-column label="回款金额(万元)" prop="money" />
        <el-table-column label="市场拓展回款绩效">
          <el-table-column label="人员" prop="deptOrUser" width="100">
            <template slot-scope="scope">
              {{ scope.row.marketExpansionRecordVo && scope.row.marketExpansionRecordVo.expansionName ? scope.row.marketExpansionRecordVo.expansionName : "" }}
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="money" width="150">
            <template slot-scope="scope">
              {{ scope.row.marketExpansionRecordVo && scope.row.marketExpansionRecordVo.money ? scope.row.marketExpansionRecordVo.money : "" }}
            </template>
          </el-table-column>
        </el-table-column>
        <el-table-column label="项目统筹人回款绩效">
          <el-table-column label="人员" prop="coordinatorId" width="100">
            <template slot-scope="scope">
              {{
                scope.row.coordinatorRecordVo
                  ? scope.row.coordinatorRecordVo.coordinatorName
                  : ""
              }}
            </template>
          </el-table-column>
          <el-table-column label="金额" prop="money" width="150">
            <template slot-scope="scope">
              {{
                scope.row.coordinatorRecordVo
                  ? scope.row.coordinatorRecordVo.money
                  : ""
              }}
            </template>
          </el-table-column>
        </el-table-column>
        <template v-if="deptList && deptList.length">
          <el-table-column label="各承担部门按回款应分配额(万元)">
            <el-table-column
              v-for="dept in deptList"
              :key="dept.deptId"
              :label="dept.deptName"
              :prop="dept.deptId"
            >
              <template slot-scope="scope">
                {{ scope.row.undertakeRecordMap && scope.row.undertakeRecordMap[dept.deptId] || "" }}
              </template>
            </el-table-column>
          </el-table-column>
        </template>
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['system:settlements:record:edit']"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handlePaymentRecordEdit(scope.row)"
            >编辑
            </el-button>
            <el-button
              v-hasPermi="['system:settlements:record:remove']"
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handlePaymentRecordDelete(scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 10px 0; text-align: right">
        <span>回款额合计：<b>{{ singleAmountPayment }}</b> 万元</span>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="paymentDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="合同回款记录管理"
      :visible.sync="paymentFormVisible"
      width="50%"
      append-to-body
    >
      <el-form :model="paymentRecordForm" label-width="80px">
        <el-form-item label="回款额">
          <el-input-number v-model="paymentRecordForm.money" style="width: 240px" controls-position="right" placeholder="请输入金额" :min="1" />
        </el-form-item>
        <el-form-item label="回款时间">
          <el-date-picker
            v-model="paymentRecordForm.payment_time"
            style="width: 240px"
            format="yyyy-MM-dd"
            type="date"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="submitPaymentRecord"
        >确 定</el-button>
        <el-button @click="cancelPaymentRecordForm">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :title="upload.title"
      :visible.sync="upload.open"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <span>仅允许导入xls、xlsx格式文件。</span>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="详情"
      :visible.sync="listByPageDialogVisible"
      width="60%"
      :before-close="handleClose"
    >
      <el-descriptions title="合同信息" :column="2" class="descriptions-list">
        <el-descriptions-item label="项目类型">{{ listDetailData.type.label }}</el-descriptions-item>
        <el-descriptions-item label="合同录入时间">{{ parseTime(listDetailData.recordTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="合同编号">{{ listDetailData.no }}</el-descriptions-item>
        <el-descriptions-item label="合同签订时间">{{ parseTime(listDetailData.signTime, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="项目名称">{{ listDetailData.projectName }}</el-descriptions-item>
        <el-descriptions-item label="区（县）">{{ listDetailData.region }}</el-descriptions-item>
        <el-descriptions-item label="业主单位">{{ listDetailData.organizationName }}</el-descriptions-item>
        <el-descriptions-item label="勘察设计公司">{{ listDetailData.company }}</el-descriptions-item>
        <el-descriptions-item label="合同金额（万元）">{{ listDetailData.money }}</el-descriptions-item>
        <el-descriptions-item label="是否为特殊合同">{{ listDetailData.isSpec === 0 ? '否': '是' }}</el-descriptions-item>
        <el-descriptions-item v-if="listDetailData.isSpec === 1" label="部门特殊比例系数">{{ listDetailData.deptSpecRate }}</el-descriptions-item>
        <el-descriptions-item v-if="listDetailData.isSpec === 1" label="市场拓展人员特殊比例系数">{{ listDetailData.expansionUserSpecRate }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-if="listDetailData.projectDeignName" title="设计责任部门" class="descriptions-list">
        <el-descriptions-item label="项目设总">{{ listDetailData.projectDeignName }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-for="item in listDetailData.projectDesignRateVos" :key="item.deptName" title="">
        <el-descriptions-item label="部门名称">{{ item.deptName }}</el-descriptions-item>
        <el-descriptions-item label="分配比例">{{ item.rate }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-if="Array.isArray(listDetailData.deptUndertakeRates) && listDetailData.deptUndertakeRates.length !== 0" title="部门承接合同应分配" class="descriptions-list">
        <template v-for="(item) in listDetailData.deptUndertakeRates">
          <el-descriptions-item :key="item.undertakeDeptName" label="部门">{{ item.undertakeDeptName }}</el-descriptions-item>
          <el-descriptions-item :key="item.undertakeDeptName" label="分配方式">{{ item.undertakeDeptIsRate === 1 ? '比例' : '金额' }}</el-descriptions-item>
          <el-descriptions-item
            :key="item.undertakeDeptName"
            :label="item.undertakeDeptIsRate === 1 ? '分配比例' : '分配金额'"
          >{{ item.undertakeDeptIsRate === 1 ? item.undertakeDeptRate : item.undertakeDeptMoney }}</el-descriptions-item>
        </template>
      </el-descriptions>
      <el-descriptions v-if="listDetailData.isDept !== null" title="市场拓展应分配" class="descriptions-list">
        <el-descriptions-item label="分配方式">{{ listDetailData.isDept?'部门':'人员' }}</el-descriptions-item>
        <el-descriptions-item v-if="!listDetailData.isDept" label="人员">{{ listDetailData.projectMarketExpansionUserName }}</el-descriptions-item>
        <el-descriptions-item v-if="listDetailData.isDept" label="部门">{{ listDetailData.projectMarketExpansionDeptName }}</el-descriptions-item>
        <el-descriptions-item label="分配比例">{{ listDetailData.projectMarketExpansionRate }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions v-if="listDetailData.projectCoordinatorName" title="项目统筹人" class="descriptions-list">
        <el-descriptions-item label="人员">{{ listDetailData.projectCoordinatorName }}</el-descriptions-item>
        <el-descriptions-item label="分配比例">{{ listDetailData.projectCoordinatorRate }}</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="其他" class="descriptions-list">
        <el-descriptions-item label="是否待定">{{ listDetailData.status===0 ?'是':'否' }}</el-descriptions-item>
        <el-descriptions-item label="备注">{{ listDetailData.remark }}</el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="listByPageDialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  delContract,
  pageContract,
  updateContract,
  downloadContractTemplate,
  downloadPaymentRecordTemplate,
  importContracts,
  importPaymentRecordTemplate,
  listDetail
} from '@/api/settlement/contract'
import {
  addPaymentRecord,
  delPaymentRecord,
  listPaymentRecord,
  editPayment
} from '@/api/settlement/paymentRecord'
import { deptList } from '@/api/settlement/dept'
import { userList } from '@/api/settlement/user'
import { parseTime } from '../../utils/ruoyi'
import ContractFormDialog from './components/ContractFormDialog.vue'

export default {
  name: 'Settlement',
  dicts: ['sys_normal_disable', 'settlement_status', 'project_types'],
  components: {
    ContractFormDialog
  },
  data() {
    return {
      paymentRecordList: [{ money: 1, recordMap: { 200: 0.5 }}],
      paymentRecordLoading: false,
      paymentFormVisible: false,
      paymentRecordForm: {},
      paymentDialogVisible: false,
      deptRateList: [],
      allocationRecords: [],
      allocationMarketRecords: [],
      allocationDialogVisible: false,
      allocationLoading: false,
      selectProjectDesignDeptRateList: [],
      userList: [],
      deptList: [],
      filteredMarketUserList: [],
      regionList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合同表格数据
      contractList: [],
      // 合计金额
      totalMoney: 0,
      totalPayment: 0,
      paymentTimeMoney: 0,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        contractName: '',
        recordDateRange: [],
        singDateRange: [],
        paymentDateRange: [],
        area: '',
        designDeptId: undefined,
        marketExpansionUserId: undefined,
        type: undefined
      },
      // 表单参数
      form: {},
      deptMap: new Map(),
      curDesignDeptRateMap: new Map(),
      // 表单校验
      rules: {
        no: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
        type: [
          { required: true, message: '合同类型不能为空', trigger: 'change' }
        ],
        recordTime: [
          { required: true, message: '录入时间不能为空', trigger: 'change' }
        ],
        projectName: [
          { required: true, message: '项目名称不能为空', trigger: 'blur' }
        ],
        region: [
          { required: true, message: '区（县）不能为空', trigger: 'blur' }
        ],
        organizationName: [
          { required: true, message: '单位不能为空', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '公司名称不能为空', trigger: 'blur' }
        ],
        money: [
          { required: true, message: '合同金额不能为空', trigger: 'blur' },
          { type: 'number', message: '合同金额必须是数字', trigger: 'blur' }
        ],
        signTime: [
          {
            required: true,
            message: '合同签订时间不能为空',
            trigger: 'change'
          }
        ],
        projectDesignLeadUserId: [
          { required: true, message: '请选择项目设总', trigger: 'change' }
        ],

        marketExpansionRate: [
          { required: true, message: '分配比例不能为空', trigger: 'blur' },
          { type: 'number', message: '分配比例必须是数字', trigger: 'blur' }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }],
        projectMarketExpansiondeptId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        projectMarketExpansionUserId: [
          { required: true, message: '请选择人员', trigger: 'change' }
        ]
      },
      reviseSection: true,
      sortVisible: false,
      editData: null,
      singleAmountPayment: 0,
      upload: {
        // 是否显示弹出层
        open: false,
        // 弹出层标题
        title: '',
        url: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0
      },
      listByPageDialogVisible: false,
      listDetailData: {
        type: { label: null },
        projectDesignRateVos: [], // 确保初始化为数组
        undertakeDeptName: null,
        undertakeDeptIsRate: null,
        undertakeDeptRate: null,
        undertakeDeptMoney: null,
        isDept: null,
        projectMarketExpansionUserName: null,
        projectMarketExpansionDeptName: null,
        no: null,
        projectCoordinatorName: null,
        projectCoordinatorRate: null,
        status: null,
        remark: null,
        recordTime: null,
        signTime: null,
        projectName: null,
        region: null,
        organizationName: null,
        company: null,
        money: null,
        isSpec: null
      }
    }
  },
  watch: {
    'form.projectDesignLeaddeptIds': {
      handler(newVal, oldVal) {
        if (!newVal || newVal.length === 0) {
          this.selectProjectDesignDeptRateList = []
          return
        }

        let change = false

        for (let i = 0; i < newVal.length; i++) {
          if (!oldVal || oldVal.length !== newVal.length) {
            change = true
            break
          }
          if (newVal[i] !== oldVal[i]) {
            change = true
            break
          }
        }
        if (change) {
          this.selectProjectDesignDeptRateList = []
          for (let i = 0; i < newVal.length; i++) {
            let rate
            if (
              this.curDesignDeptRateMap &&
              this.curDesignDeptRateMap.size > 0
            ) {
              rate = this.curDesignDeptRateMap.get(newVal[i])
            }
            this.selectProjectDesignDeptRateList.push({
              deptId: newVal[i],
              rate: rate
            })
          }
        }
      },
      deep: true
    },
    userList: {
      handler(val) {
        this.filteredMarketUserList = val || []
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.getUserList()
    this.getDeptList()
    this.getRegionList()
  },
  methods: {
    parseTime,
    enableSubmit() {
      if (
        !this.selectProjectDesignDeptRateList ||
        this.selectProjectDesignDeptRateList.length === 0
      ) {
        return true
      }
      for (let i = 0; i < this.selectProjectDesignDeptRateList.length; i++) {
        const rate = this.selectProjectDesignDeptRateList[i].rate
        if (!rate) {
          return false
        }
      }
      return true
    },
    handlePaymentRecordDialog(row) {
      this.paymentDialogVisible = true
      this.curContractId = row.id
      this.paymentRecordList = [] // 先清空，避免上次数据残留
      this.singleAmountPayment = 0 // 同步清空合计
      this.getPaymentRecordList(this.curContractId)
    },
    handleViewAllocation(row) {
      this.allocationRecords = row.deptRateList
      this.allocationMarketRecords = [
        {
          projectMarketExpansionUserName: row.projectMarketExpansionUserName,
          projectMarketExpansionDeptName: row.projectMarketExpansionDeptName,
          marketExpansionRate: row.marketExpansionRate,
          marketExpansionMoney: row.marketExpansionMoney,
          isDept: row.isDept
        }
      ]
      this.allocationDialogVisible = true
    },

    getList() {
      this.loading = true
      // 处理时间区间参数
      const params = { ...this.queryParams }
      if (params.recordDateRange && params.recordDateRange.length === 2) {
        const recordTimeStart = new Date(params.recordDateRange[0]).setHours(
          0,
          0,
          0,
          0
        )
        const recordTimeEnd = new Date(params.recordDateRange[1]).setHours(
          23,
          59,
          59,
          999
        )
        params.recordDateRange = [recordTimeStart, recordTimeEnd]
      }
      if (params.singDateRange && params.singDateRange.length === 2) {
        const signTimeStart = new Date(params.singDateRange[0]).setHours(
          0,
          0,
          0,
          0
        )
        const signTimeEnd = new Date(params.singDateRange[1]).setHours(
          23,
          59,
          59,
          999
        )
        params.singDateRange = [signTimeStart, signTimeEnd]
      }
      if (params.paymentDateRange && params.paymentDateRange.length === 2) {
        const paymentTimeStart = new Date(params.paymentDateRange[0]).setHours(
          0,
          0,
          0,
          0
        )
        const paymentTimeEnd = new Date(params.paymentDateRange[1]).setHours(
          23,
          59,
          59,
          999
        )
        params.paymentDateRange = [paymentTimeStart, paymentTimeEnd]
      }
      params.isNoDesc = this.sortVisible ? 1 : 0
      pageContract(params).then((res) => {
        const data = res.data
        this.contractList = data.pageInfo.list || []
        // 合计
        this.totalMoney = data.totalMoney
        this.totalPayment = data.totalPaymentMoney
        this.paymentTimeMoney = data.paymentTimeMoney
        this.contractList.forEach((item) => {
          item.status = '' + item.status
          item.isSpec = item.isSpec === 1
          if (item.projectDesignLeaddeptIds) {
            item.projectDesignLeaddeptIds =
              item.projectDesignLeaddeptIds.split(',')
            const arr = []
            item.projectDesignLeaddeptIds.forEach((id) => {
              arr.push(parseInt(id))
            })
            item.projectDesignLeaddeptIds = arr
          }
        })
        this.total = data.pageInfo.total
        this.loading = false
      })
    },
    getPaymentRecordList(contractId) {
      this.paymentRecordLoading = true
      // 兼容未传参时用 curContractId
      const id = contractId || this.curContractId
      if (!id) {
        this.paymentRecordList = []
        this.singleAmountPayment = 0
        this.paymentRecordLoading = false
        return
      }
      listPaymentRecord(id).then((res) => {
        this.paymentRecordList = res.data || []
        this.singleAmountPayment = (res.data || [])
          .reduce((total, item) => {
            return total + (Number(item.money) || 0)
          }, 0)
          .toFixed(2)
        this.paymentRecordLoading = false
      }).catch(() => {
        this.paymentRecordList = []
        this.singleAmountPayment = 0
        this.paymentRecordLoading = false
      })
    },
    getDeptList() {
      deptList().then((res) => {
        this.deptList = res.data
        this.deptMap = new Map()
        if (this.deptList && this.deptList.length > 0) {
          this.deptList.forEach((item) => {
            this.deptMap.set(item.deptId, item.deptName)
          })
        }
      })
    },
    getUserList() {
      userList().then((res) => {
        this.userList = res.data
      })
    },
    getRegionList() {
      pageContract({ pageNum: 1, pageSize: 10000 }).then((res) => {
        const data = res.data && res.data.list ? res.data.list : []
        const set = new Set()
        data.forEach((item) => {
          if (item.region) set.add(item.region)
        })
        this.regionList = Array.from(set)
      })
    },
    cancelPaymentRecordForm() {
      this.paymentFormVisible = false
      this.paymentRecordForm = {}
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        contractName: '',
        recordDateRange: [],
        singDateRange: [],
        paymentDateRange: [],
        area: '',
        designDeptId: undefined,
        marketExpansionUserId: undefined
      }
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.roleId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handlePaymentRecordAdd() {
      this.paymentFormVisible = true
      this.paymentRecordForm = {}
      this.editPaymentRecordId = null
    },
    handlePaymentRecordEdit(row) {
      this.paymentFormVisible = true
      this.editPaymentRecordId = row.id
      this.paymentRecordForm = {
        id: row.id,
        money: row.money,
        payment_time: row.paymentTime ? new Date(row.paymentTime) : null
      }
    },
    handleAdd() {
      this.title = '添加合同'
      this.editData = {
        type: 2,
        isDept: false,
        status: '1'
      }
      this.open = true
    },
    handleUpdate(row) {
      this.title = '修改合同'
      this.editData = { ...row }
      this.open = true
    },
    handleSort() {
      this.sortVisible = !this.sortVisible
      this.getList()
    },
    submitPaymentRecord: function() {
      if (this.editPaymentRecordId) {
        // 编辑回款记录
        const paymentTime = this.paymentRecordForm.payment_time instanceof Date
          ? this.paymentRecordForm.payment_time.getTime()
          : this.paymentRecordForm.payment_time
        editPayment(this.editPaymentRecordId, this.paymentRecordForm.money, paymentTime).then(() => {
          this.$modal.msgSuccess('编辑成功')
          this.paymentFormVisible = false
          this.getPaymentRecordList()
          this.getList()
        })
      } else {
        // 新增回款记录
        const date = new Date(this.paymentRecordForm.payment_time)
        const payment_time = date.getTime()
        addPaymentRecord(
          this.curContractId,
          this.paymentRecordForm.money,
          payment_time
        ).then((response) => {
          this.$modal.msgSuccess('新增成功')
          this.paymentFormVisible = false
          this.getPaymentRecordList()
          this.getList()
        })
      }
    },
    // 新增/修改合同时将时间字段转为时间戳
    onContractFormSuccess() {
      this.open = false
      this.getList()
    },
    deptListToDeptRateList(deptList) {
      const deptRateList = []
      deptList.forEach((item) => {
        if (item.rate || item.money) {
          const deptRate = {
            deptId: item.deptId,
            rate: item.isMoney ? 0 : item.rate,
            money: item.isMoney ? item.money : 0,
            isRate: !item.isMoney ? 1 : 0
          }
          deptRateList.push(deptRate)
        }
      })
      return deptRateList
    },
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除合同编号为"' + row.no + '"的数据项？')
        .then(function() {
          return delContract(row.id)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handlePaymentRecordDelete(row) {
      this.$modal
        .confirm('是否确认删除回款记录id为"' + row.id + '"的数据项？')
        .then(function() {
          return delPaymentRecord(row.id)
        })
        .then(() => {
          this.getPaymentRecordList()
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleExport(type) {
      if (type === '合同') {
        downloadContractTemplate()
          .then((response) => {
            // 创建下载链接
            const url = window.URL.createObjectURL(new Blob([response]))
            const link = document.createElement('a')
            link.href = url

            // 从响应头获取文件名，或者使用默认文件名
            const fileName = '合同模版.xlsx'

            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()

            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          })
          .catch((error) => {
            console.error('下载失败:', error)
            // 可以在这里添加错误提示
          })
      } else {
        downloadPaymentRecordTemplate()
          .then((response) => {
            // 创建下载链接
            const url = window.URL.createObjectURL(new Blob([response]))
            const link = document.createElement('a')
            link.href = url

            // 从响应头获取文件名，或者使用默认文件名
            const fileName = '回款记录模版.xlsx'

            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()

            // 清理
            document.body.removeChild(link)
            window.URL.revokeObjectURL(url)
          })
          .catch((error) => {
            console.error('下载失败:', error)
            // 可以在这里添加错误提示
          })
      }
    },
    handleTypeChange(value) {
      this.reviseSection = value !== '1'
    },
    filterMarketUser(query) {
      if (!query) {
        this.filteredMarketUserList = this.userList
      } else {
        this.filteredMarketUserList = this.userList.filter(
          (u) => u.nickName && u.nickName.indexOf(query) !== -1
        )
      }
    },
    /** 导入按钮操作 */
    handleImport(type) {
      this.upload.title = type === '合同' ? '合同模版导入' : '回款记录模版导入'
      this.upload.open = true
      this.$nextTick(() => {
        this.$refs.upload.clearFiles() // 清除之前的文件
      })
    },
    // 文件上传进度处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
          response.msg +
          '</div>',
        '导入结果',
        { dangerouslyUseHTMLString: true }
      )
      this.getList()
    },
    // 提交上传文件
    submitFileForm() {
      const fileList = this.$refs.upload.uploadFiles
      console.log('🚀 ~ submitFileForm ~ fileList:', fileList)
      if (fileList.length === 0) {
        this.$message.warning('请先选择文件')
        return
      }

      const formData = new FormData()
      const name =
        this.upload.title === '合同模版导入'
          ? 'contractExcelFile'
          : 'paymentRecordExcelFile'
      formData.append(name, fileList[0].raw) // 确保使用原始文件对象

      this.upload.isUploading = true

      // 根据不同类型调用不同接口
      const importRequest =
        this.upload.title === '合同模版导入'
          ? importContracts(formData)
          : importPaymentRecordTemplate(formData)

      importRequest
        .then((response) => {
          this.handleFileSuccess(response)
        })
        .catch((error) => {
          this.upload.isUploading = false
          this.$message.error('导入失败: ' + (error.message || '未知错误'))
        })
    },
    tableRowClassName({ row }) {
      if (row.status === '0') {
        return 'error-row'
      }
      return ''
    },
    handleListShow(row) {
      this.listByPageDialogVisible = true
      listDetail(row.id).then(res => {
        this.listDetailData = res.data
        if (this.listDetailData.type) {
          this.listDetailData.type = this.dict.type.project_types.find(item => Number(item.value) === this.listDetailData.type)
        }
      })
    },
    handleClose() {
      this.listByPageDialogVisible = false
      this.listDetailData = {
        type: { label: null },
        projectDesignRateVos: [], // 确保初始化为数组
        undertakeDeptName: null,
        undertakeDeptIsRate: null,
        undertakeDeptRate: null,
        undertakeDeptMoney: null,
        isDept: null,
        projectMarketExpansionUserName: null,
        projectMarketExpansionDeptName: null,
        no: null,
        projectCoordinatorName: null,
        projectCoordinatorRate: null,
        status: null,
        remark: null,
        recordTime: null,
        signTime: null,
        projectName: null,
        region: null,
        organizationName: null,
        company: null,
        money: null,
        isSpec: null
      }
    }
  }
}
</script>
<style>
.section-divider {
  margin: 20px 0;
  text-align: center;
  font-weight: bold;
  border-top: 1px solid #eee;
  padding-top: 10px;
}
.el-table .error-row {
  background: rgb(255, 162, 162);
}
.descriptions-list{
  margin-top: 10px;
}
.el-descriptions__header{
  margin-bottom: 4px;
}
</style>
